<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <script>
        let arr1 = [1, 2, [4, 5, 6]];
        let arr2 = arr1.slice(0);

        arr2[2].push(7);
        arr2[1]++;

        console.log(arr1)
        console.log(arr2)

        let obj = {
            a: 1,
            b: "hello",
            c: [1, 2, 3],
            d: { e: "world" },
            f: function () {
                console.log("hello world");
            },
        }


        //手动封装一个cloneDeep方法,手动实现一个深拷贝的操作
        function cloneDeep(obj, map = new WeakMap()) {
            let cloneObj = {};
            //判断一些特殊情况的操作
            if (obj === null) return null;
            if (obj instanceof Date) return new Date(obj);
            if (obj instanceof RegExp) return new RegExp(obj);
            //判断对象是否拷贝过，如果拷贝过就直接返回
            if (map.get(obj)) return map.get(obj);

            for (let key in obj) {
                if (typeof obj[key] != null && typeof obj[key] == "object") {
                    map.set(obj, cloneObj);
                    cloneObj[key] = cloneDeep(obj[key], map);
                } else {
                    cloneObj[key] = obj[key];
                }
            }
            return cloneObj;
        }
        
        let obj2 = cloneDeep(obj);
        obj.c.push(3);
        obj2.d.e = "Liguanh";
        console.log(obj2);
        console.log(obj);
    </script>
</body>

</html>